from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("Sane-backends MCP Server")

"""
面向软件：sane-backends

MCP tools 列表：
1. sane_socket_test_execution - 测试 saned.socket 服务的执行状态
   参数：无
   返回：统一的 JSON 结构

2. sane_socket_test_reload - 测试 saned.socket 服务的重载功能
   参数：无
   返回：统一的 JSON 结构
"""

@mcp.tool()
def sane_socket_test_execution() -> Dict[str, Any]:
    """
    测试 saned.socket 服务的执行状态
    
    用途：验证 saned.socket 服务的基本执行功能
    参数：无
    返回 JSON 结构：
    {
        "success": bool,      # 命令执行是否成功
        "command": str,       # 执行的完整命令
        "exit_code": int,     # 命令退出码
        "stdout": str,        # 标准输出
        "stderr": str         # 标准错误
    }
    """
    command = "systemctl status saned.socket"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def sane_socket_test_reload() -> Dict[str, Any]:
    """
    测试 saned.socket 服务的重载功能
    
    用途：验证 saned.socket 服务的重载操作
    参数：无
    返回 JSON 结构：
    {
        "success": bool,      # 命令执行是否成功
        "command": str,       # 执行的完整命令
        "exit_code": int,     # 命令退出码
        "stdout": str,        # 标准输出
        "stderr": str         # 标准错误
    }
    """
    command = "systemctl reload saned.socket"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()